<template>

    <el-form label-width="80px">
        <el-avatar  :model="formData.headIconUrl" :size="100" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"/>

        <el-form-item label="用户名">
            <el-input v-model="formData.userName" :disabled="!isEditing" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别">
            <el-radio-group v-model="formData.sex" size="large" :disabled="!isEditing">
                <el-radio-button label="男" />
                <el-radio-button label="女" />
            </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
            <el-slider v-model="formData.age" show-input size="large" :disabled="!isEditing"/>
        </el-form-item>
        <el-form-item label="地址">
            <el-input v-model="formData.locate" clearable :disabled="!isEditing"></el-input>
        </el-form-item>
        <el-form-item label="身份证号">
            <el-input v-model="formData.idCard" clearable :disabled="!isEditing"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
            <el-input v-model="formData.tel" clearable :disabled="!isEditing"></el-input>
        </el-form-item>
        <el-form-item label="菜系标签">
            <el-checkbox-group v-model="formData.tags" size="large" :disabled="!isEditing">
                <el-checkbox-button v-for="city in cities" :key="city" :label="city" border >
                    {{ city }}
                </el-checkbox-button>
            </el-checkbox-group>
        </el-form-item>




        <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item title="设定菜价">
        <div  class="dish-item"  v-for="dishItem in selectedDish.data" :key="dishItem.dishName" >
            <el-select v-model="dishItem.dishName" placeholder="请选择菜品" @change="handleSelection" :disabled="!isEditing" style="margin-right:20px">
                <el-option v-for="dish in dishSrcData.data" :label="dish.dish_name" :key="dish.id" :value="dish.dish_name"></el-option>
            </el-select>
            <el-input-number v-model="dishItem.dishPrice" :precision="2" :step="0.1" :min="0" :max="1000" :disabled="!isEditing"/>
        </div>
            <el-button type="primary" @click="addOptionData" :icon="Plus" circle :disabled="!isEditing"/>
            <el-button type="danger" @click="reduceOptionData" :icon="Minus" circle :disabled="!isEditing"></el-button>

        </el-collapse-item>
            </el-collapse>





        <el-form-item >
            <el-button class="myButton" v-if="!isEditing" type="primary" @click="startEditing" :icon="Edit" :size='large'>编辑</el-button>
            <el-button class="myButton" v-else type="success" @click="saveUser" :icon="Check" :size='large'>保存</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from "vue";
import {Check, Edit, Plus, Minus} from "@element-plus/icons-vue";
import {ElMessage, ElNotification} from "element-plus";
const { proxy } = getCurrentInstance()
let isEditing = ref(false)

let currentUser = reactive({
    name:'',
    id:0
})

let dishSrcData = reactive({
    data: []
})

let formData = reactive({
    id:'',
    headIconUrl:'',
    userName:'',
    sex:'',
    age:'',
    locate:'',
    idCard:'',
    tel:'',
    tags:''
})
let selectedDish = reactive({
    data:[]
});
let dishItemData = reactive({
    dishName:'',
    dishPrice:''
})


function addOptionData() {
    selectedDish.data.push(Object.assign({}, dishItemData))
}

function reduceOptionData() {
    if (selectedDish.data.length > 0) {
        // 删除最后一个属性
        selectedDish.data.pop();
    }
}

let cities = reactive([
    "鲁菜",
    "川菜",
    "粤菜",
    "苏菜",
    "闽菜",
    "浙菜",
    "湘菜",
    "徽菜",
    "法式",
    "意式",
    "日式",
    "墨式",
    "美式",
    "韩式"
])
function startEditing(){
    isEditing.value = true
}

function saveUser(){
    updateInfo()
    isEditing.value = false;
}
function convertNameToId(name) {
    const dish = dishSrcData.data.find(item => item.dish_name === name);
    return dish ? dish.id : null;
}
const updateInfo = () => {
    const tarData = Object.assign({}, formData);    // 显式复制对象
    tarData.tags = tarData.tags.map(obj => JSON.stringify(obj)
        .replace(/"/g, '')
        .replace(/\\/g, ''))
        .join('|')
    proxy.$axios.patch(`${proxy.serCtx}/userBase/updateUserInfo`, tarData).then(() => {
        // ElNotification({
        //     title: '成功',
        //     message: '用户信息已更新',
        //     type: 'success',
        // })
    })

// 遍历 selectedDish.data 中的 dishName
    const tempSelectDish = JSON.parse(JSON.stringify(selectedDish.data));
    // let tempSelectDish = Object.assign({}, selectedDish.data)
    tempSelectDish.forEach(dishItem => {
        const dishId = dishItem.dishName;
        dishItem.dishName = convertNameToId(dishId);

    });

    const requestData = {
        data: tempSelectDish,
        id: currentUser.id
    };

    proxy.$axios.patch(`${proxy.serCtx}/userBase/updateCookerDetailInfo`, requestData).then(() => {
        ElNotification({
            title: '成功',
            message: '用户信息已更新',
            type: 'success',
        });
    });
}


const Info = () => {
    let path = `${proxy.serCtx}/userBase/userDataById`
    proxy.$axios.get(path, {
        params:{
            id: currentUser.id
        }
    }).then((res) => {
        formData.id = res.data.id
        formData.headIconUrl = res.data.headIconUrl
        formData.userName = res.data.userName
        formData.sex = res.data.sex
        formData.age = res.data.age
        formData.locate = res.data.locate
        formData.idCard = res.data.idCard
        formData.tel = res.data.tel
        formData.tags = res.data.tags.split('|')
    })

    let dishPath = `${proxy.serCtx}/userBase/getAllDish`
    proxy.$axios.get(dishPath).then((res) => {
        if(res.data.length === 0) {
            ElMessage("没有找到菜单数据")
            return;
        }
        dishSrcData.data = res.data;
    })

    let detailPath = `${proxy.serCtx}/userBase/message`
    proxy.$axios.get(detailPath, {
        params:{
            id: currentUser.id
        }
    }).then((res) => {
        let dishNumsStr = res.data.cookerDetailVO.dish.split('|')
        let dishPriceStr = res.data.cookerDetailVO.price.split('|')
        for(let i = 0; i < dishNumsStr.length; i++) {
            let dishItem = Object.assign({}, dishItemData)
            dishItem.dishName = res.data.cookerDetailVO.foodsInfo[i].foodName
            dishItem.dishPrice = dishPriceStr[i]
            selectedDish.data.push(dishItem)
        }
    })
}

onMounted(()=> {
    currentUser.id = JSON.parse(localStorage.getItem('id'))
    currentUser.name = JSON.parse(localStorage.getItem('name'))
    Info()
})



//
const activeNames = ref([]);

// const selectedDishPrice = ref(null);
// const dishes = ref([
//     { id: '1', name: 'ww',price:'5'},
//     { id: '2', name: 'w',price:'4' },
//     { id: '3', name: 'w',price:'8'},
// ]);
function handleSelection() {
    // 处理下拉菜单选择事件
}
function handleChange() {
    // 处理折叠事件
}
//




</script>

<style scoped>
.myButton{
    width: 500px;
    margin: 0 auto;
}
.dish-item {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ccc;
}
</style>